package com.ycwl.aiLive_2d.thread;

import com.ycwl.aiLive_2d.exception.BaseException;
import com.ycwl.aiLive_2d.utils.AudioUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 弃用
 *
 * @author songmingsong
 * @date 2023/7/7
 */
@Slf4j
public class MouthThreadReturn implements Runnable {

    private String uid;

    private String audioPath;

    public MouthThreadReturn(String uid, String audioPath) {
        this.uid = uid;
        this.audioPath = audioPath;
    }

    public static Map<String, Object> queueMap = new HashMap<>();
    /**
     * 是否正在解析
     */
    public static Map<String, String> isPaseMap = new HashMap<>();

    @Override
    public void run() {
        log.info("[线程]->启动语音解析线程");
        Object returnValue = getMouthList(uid);// 格式[1,2,3]
        //queueMap.put(uid, returnValue);
        log.info("[线程]->解析出来的总数据：{}", returnValue);
    }

    /**
     * 使用Java代码
     * 获取语音嘴巴弧度数据
     *
     * @return
     */
    private List<Double> getMouthList(String uid) {
        String wavPath = this.getClass().getResource("/").toString();
        if (wavPath.startsWith("file:")) {
            wavPath = wavPath.substring("file:/".length());
        }
        String audioPath = wavPath + uid + "/streaming_tts.wav";
        List<Double> doubleList = AudioUtils.processAudio(audioPath, uid);
        return doubleList;
    }


    /**
     * 使用python代码
     * 获取语音嘴巴弧度数据
     *
     * @return
     */
    private Object getMouthListByPython() {
        Map<String, Object> map = new HashMap<>(1);
        Process proc;
        try {
            String wavPath = this.getClass().getResource("/").toString();
            if (wavPath.startsWith("file:")) {
                wavPath = wavPath.substring("file:/".length());
            }
            String pythonPath = wavPath + "/python/mouth.py";
            String[] args1 = new String[]{"python", pythonPath, wavPath + uid + "/streaming_tts.wav"};
            proc = Runtime.getRuntime().exec(args1);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "gb2312"));
            String line = null;
            while ((line = in.readLine()) != null) {
                map.put("data", line);
            }
            in.close();
            proc.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("嘴行弧度转换异常", 5001);
        }
        return map.get("data");
    }

}
